<template>
  <div class="app-container">
    <div v-for="(item,index) in list" :key="index"  style="margin-bottom: 24px;">
      <el-card>
        <el-row >
          <el-col :xs="12" :sm="8" :md="8" :lg="4" :xl="4" style="margin: 12px 0">
            <div style="margin-right: 24px">
              <div>
                <span style="font-size: 14px;width: 60px;display: inline-block;text-align: right;">角色名称</span>
                <el-input v-model="item.roleName" placeholder="请输入角色名称" style="width: calc(100% - 72px);margin-left: 12px" size="small"></el-input>
              </div>
              <div style="margin-top: 12px">
                <span style="font-size: 14px;width: 60px;display: inline-block;text-align: right;">层级</span>
                <el-select v-model="item.stratum" placeholder="请选择层级" style="width: calc(100% - 72px);margin-left: 12px" size="small">
                  <el-option v-for="item in 9" :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </div>
            </div>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4" v-for="(goods,goodsIndex) in item.roleGoodsDTOList" :key="goodsIndex" style="margin: 12px 0">
            <div v-for="(good,goodIndex) in goods" :key="goodIndex" :style="{marginTop:goodIndex === 1 ? '12px':'0'}">
              <span style="font-size: 14px;width: 100px;display: inline-block;text-align: right;">
                {{
                  good.goodsName || '无'
                }}</span>
              <el-input v-model="good.price" @change="(val)=>changePrice(val,good,index,goodsIndex,goodIndex)" placeholder="请输入金额" style="width: calc(100% - 72px - 65px);margin-left: 12px" size="small">
                <template slot="prepend">￥</template>
              </el-input>
            </div>
          </el-col>
        </el-row>
        <div class="drop-role" v-show="item.id != 3 && item.id != 4 && item.id != 5 && item.id != 6" @click="dropRole(index)">
          删除
        </div>
      </el-card>
    </div>
    <div class="add-role"><span  @click="addRoleList">新增角色</span></div>
    <div class="save-button-box">
      <div class="save-button" @click="submit">
        保存设置
      </div>
    </div>
  </div>
</template>
<script>

import {listRole, updateGoodsRole} from "@/api/system/distribution";
import {isValidAmount} from "@/utils/ruoyi";

export default {
  name: "",
  components: {},
  data() {
    return {
      list: [],
    };
  },
  created() {
    this.getList()
  },
  mounted() {
  },
  methods: {
    dropRole(index) {
      this.$confirm("是否确定删除改角色?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        this.list.splice(index, 1)
      })
    },
    addRoleList() {
      let roleGoodsDTOList = JSON.parse(JSON.stringify(this.list[0].roleGoodsDTOList))
      roleGoodsDTOList.forEach(item => {
        item.forEach(good => {
          good.price = 0
        })
      })
      this.list.push({
        roleName: '',
        stratum: 1,
        roleGoodsDTOList
      })
    },
    submit() {
      // 校验角色名称、层级、金额是否为空
      for (let i = 0; i < this.list.length; i++) {
        // stratum可以等于数字0，但是roleName和stratum不能为空
        if (!this.list[i].roleName) {
          this.$message.error(`请填写第${i + 1}个角色的名称`)
          return
        }
        if (!this.list[i].stratum && this.list[i].stratum !== 0) {
          this.$message.error(`请填写第${i + 1}个角色的层级`)
          return
        }
      }
      for (let i = 0; i < this.list.length; i++) {
        for (let j = 0; j < this.list[i].roleGoodsDTOList.length; j++) {
          for (let k = 0; k < this.list[i].roleGoodsDTOList[j].length; k++) {
            if (!this.list[i].roleGoodsDTOList[j][k].price) {
              this.$message.error(`请填写第${i + 1}个角色的${this.list[i].roleGoodsDTOList[j][k].goodsName}金额`)
              return
            }
          }
        }
      }
      let data = JSON.parse(JSON.stringify(this.list))
      data.forEach(item => {
        item.roleGoodsDTOList = this.convertTo1DArray(item.roleGoodsDTOList)
      });
      updateGoodsRole(data).then(res => {
        this.$message.success("保存成功")
      })
    },
    getList() {
      listRole().then(res => {
        this.list = res.rows
        this.list.forEach(item => {
          item.roleGoodsDTOList = this.convertTo2DArray(item.roleGoodsDTOList)
        });
        this.sourceList = JSON.parse(JSON.stringify(this.list))
      });
    },
    changePrice(val, good, index, goodsIndex, goodIndex) {
      if (!isValidAmount(val)) {
        this.$message.error("金额格式不正确")
        this.list[index].roleGoodsDTOList[goodsIndex][goodIndex].price = this.sourceList[index].roleGoodsDTOList[goodsIndex][goodIndex].price
        return
      }
    },
    convertTo2DArray(arr) {
      const result = [];
      for (let i = 0; i < arr.length; i += 2) {
        // 如果只有一个元素，单独成组
        if (i + 1 < arr.length) {
          result.push([arr[i], arr[i + 1]]);
        } else {
          result.push([arr[i]]);
        }
      }
      return result;
    },
    convertTo1DArray(arr) {
      return arr.reduce((result, sublist) => result.concat(sublist), []);
    }
  }
}
</script>
<style lang="scss">
.add-role {
  color: blue;
  text-decoration: underline;
  text-align: center;
  margin: 24px 0;
}
.add-role span {
  cursor: pointer;
}

.drop-role {
  color: blue;
  text-decoration: underline;
  margin: 12px 0;
  cursor: pointer;
}

.save-button-box {
  display: flex;
  align-items: center;
  justify-content: center
}

.save-button {
  margin: 24px auto;
  display: inline-block;
  border: 1px solid #ccc;
  padding: 6px 32px;
  font-size: 14px;
  cursor: pointer;
}
</style>
